package com.liusha.quicksand.web;

import com.liusha.quicksand.po.User;
import com.liusha.quicksand.po.UserLogin;
import com.liusha.quicksand.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 一世长安一世欢
 * @Date: 2020/10/18
 * @Time: 15:06
 * @Description: No Description
 */

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    /*  网站登录页 */
    @GetMapping("/login")
    public String login(Model model) {

        model.addAttribute("userLogin", new UserLogin());

        return "login";
    }

    @PostMapping("/login")
    public String login(@Validated UserLogin user, BindingResult result,
                        HttpSession session, Model model, RedirectAttributes attributes) {

        if (result.hasErrors()) {
            return "redirect:/login";
        }

        User user1 = userService.checkUsers(user);
        if (user1 != null) {
            session.setAttribute("user", user1);
//            System.out.println("登录成功！！");
//            System.out.println(user1.getNickname());
            attributes.addFlashAttribute("message","欢迎您"+ user1.getNickname());
            return "redirect:/index";
        }

        attributes.addFlashAttribute("message", "登录失败！！！");

        model.addAttribute("fail", "账号或密码不正确！");

        return "redirect:/login";
    }


    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/index";
    }
}
